<?php
	/**
	 * 框架基类
	 * MVC三者的通讯中间层及配置参数
	 * @todo
	 * @author swingcoder <swingcoder@msn.com>
	 * @version 0.1
	 * @copyright Copyright (c) 2009, swingcoder.com
	 */

	class base
	{
		var $_config = array();
		var $load_object = array();
		var $get = array();
		var $post = array();
		var $cookie = array();
		var $server = array();
		var $input = array();
		var $files = array();
		var $env = array();
		var $_lang = array();
		var $browser = '/(msie|maxthon|tencenttraveler|gecko|mozilla|firebird|firefox|netscape|safari|konqueror|opera|hotjava)/i';

		public function base()
		{
			require '../inc/config.inc.php';

			$curr_browser_lang = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? strtolower( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) : '';

			if ( strpos( $curr_browser_lang, 'zh' ) === false )
			{
				require $_config[ 'dir' ][ 'lang' ] . 'en.php';	//不可使用require_once
			}
			else
			{
				require $_config[ 'dir' ][ 'lang' ] . 'zh_cn.php';	//不可使用require_once
			}
			$this->_lang = $_lang;

			$this->_config = $_config;

			$this->base_init();
		}

		final private function base_init()
		{
			$sid = session_id();
			if ( preg_match( $this->browser, $_SERVER['HTTP_USER_AGENT'] ) &&  empty( $sid ) )
			{
				session_start();
			}

			$this->set_context();
		}

		public function set_context()
		{
			$this->get = &$_GET;
			$this->post = &$_POST;
			$this->cookie = &$_COOKIE;
			//$this->input = array_merge( $this->get, $this->post );
			$this->input = &$_REQUEST;	 //include $_GET,$_POST,$_COOKIE
			$this->server = &$_SERVER;
			$this->files = &$_FILES;
			$this->env = &$_ENV;
			$this->session = &$_SESSION;
		}

		public function module( $m, $args = array() )
		{
			$obj_name = $m;
			if( strpos($m, '.') > 0 )
			{
				$m = str_replace( '.', DS, $m);
				$obj_name = substr( $m, strrpos($m, DS) + 1 );
			}
			if( ! isset( $this->load_object[$obj_name] ) )
			{
				$this->load_object[$obj_name] = $this->load( $m, $obj_name, $args );
			}

			return $this->load_object[$obj_name];
		}

		public function load( $m, $obj_name, $args=array() )
		{
			$module_file = $this->_config[ 'dir' ][ 'root' ] . $m . '.php';

			if( is_file( $module_file ) )
			{
				require_once $module_file;

				$module_obj = new $obj_name( $args );

				if( is_object($module_obj) )
				{
					return $module_obj;
				}
				else
				{
					trigger_error( '[load module] ' . $m . ' object init failure.', E_USER_ERROR);
				}
			}
			else
			{
				trigger_error( '[load module] File ' . $module_file . ' does not exists.', E_USER_ERROR);
			}
		}

		public function view( $tplname='', $data=array() )
		{
			require_once 'view.php';

			$view = new view();

			$view->render( $tplname, $data );
		}
	}
?>